import React, { useEffect, useState, useRef } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Input, Select, Form, Radio, Button, Upload, Modal, message } from "antd";
import {
  UserEdit,
  userGet,
  userAdd,
} from "../../../request/xxApi";
import Department from "../../../styles/AddAccount.module.css";
import "../../../assets/xxAssets/font_4791525_1loqcwtpe32h/iconfont.css";
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

function AddAccount() {
  const [deteleid, setdeteleid] = useState(); //删除的数据id
  const [doctorAll, setDoctorAll] = useState(); //所有权限的信息下拉框使用
  const [form] = Form.useForm(); //表单
  const currentRecordRef = useRef();
  const [userinfo, setUserinfo] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [file, setFile] = useState(null); //上传返回图片的路径

  useEffect(() => {
    //获取所有数据将权限筛选出来
    userGet({ page: 1, size: 100 }).then((res) => {
      res.data.forEach((item) => {
        if (userinfo.indexOf(item.purview) === -1) {
          setUserinfo([...userinfo, item.purview]);
        }
        const doctors = userinfo.map((doctor) => ({
          label: doctor,
          value: doctor,
        }));
        setDoctorAll(doctors);
      });
    });
  });

 

  const handlePreview = (file) => {
    console.log(file.response.header);
    if (!file.url && !file.preview) {
      file.preview = getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
    );
  };
  //图片上传
  const handleChange = (info) => {
    const { fileList } = info;
    setFile(() => {
      if (fileList.length === 1) {
        return fileList[0];
      }
      return null;
    });
    console.log(fileList[0].response?.header);
    form.setFieldsValue({
        head: fileList[0].response?.header,
      });
  };
  const handleOkItemClick = async () => {
    // 触发表单验证
    try {
      await form.validateFields();
      // 如果验证通过，获取表单值
      const formData = form.getFieldsValue();
      console.log(formData); // 打印表单数据
      // 调用 API 提交表单数据
      userAdd(formData).then(res => {
        console.log(res);
        if (res && res.code === 1) { // 假设200是成功的状态码
          message.success('创建成功');
          form.resetFields();
        } else {
          message.error('创建失败');
        }
      });
    } catch (errorInfo) {
      // 验证失败，显示错误信息
      message.error('请填写所有必填项');
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const handleCancel = () => {
    setPreviewOpen(false);
  };
  const validateRules = {
    account: [
    ],
    purview: [{ required: true, message: '请选择权限' }],
    password: [{ required: true, message: '请输入密码' }],
    ConfirmPassword: [
      { required: true, message: '请确认密码' },
      { validator: (_, value, callback) => {
        if (value && value !== form.getFieldValue('password')) {
          callback('两次输入的密码不匹配!');
        } else {
          callback();
        }
      }}
    ],
    name: [{ required: true, message: '请输入医务人员姓名' }],
    sex: [{ required: true, message: '请选择性别' }],
    idcard: [
      { required: true, message: '请输入身份证号' },
      { pattern: /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/, message: '身份证号格式不正确' }
    ],
    phone: [
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
    ],
  };

  return (
    <div>
      <Form
        onFinish={handleOkItemClick}
        form={form}
        style={{
          marginTop: "20px",
          maxWidth: 600,
        }}
      >
        <Form.Item className={Department.account} name="account" labelCol={{ span: 4 }} rules={validateRules.account} label="医务账号">
          <Input placeholder="请输入账号/手机号/邮箱" />
        </Form.Item>
        <Form.Item className={Department.account} name="purview" labelCol={{ span: 4 }} rules={validateRules.purview} label="账号权限">
          <Select placeholder="选择权限" options={doctorAll} />
        </Form.Item>
        <Form.Item className={Department.account} name="department" labelCol={{ span: 4 }}  label="科室">
          <Input length='11' placeholder="请输入该医务人员的科室" />
        </Form.Item>
        <Form.Item className={Department.account} name="password" rules={validateRules.password} labelCol={{ span: 4 }} label="医务密码">
          <Input placeholder="请输入密码" />
        </Form.Item>
        <Form.Item
        className={Department.account}
        rules={validateRules.ConfirmPassword}
          name="ConfirmPassword"
          labelCol={{ span: 4 }}
          label="确认密码"
        >
          <Input
            placeholder="请确认密码"
            value={currentRecordRef.current ? currentRecordRef.current.id : ""}
          />
        </Form.Item>
        
        <Form.Item className={Department.account} name="name" labelCol={{ span: 4 }} label="医务姓名">
          <Input
            placeholder="请输入该医务人员姓名"
            value={
              currentRecordRef.current ? currentRecordRef.current.phone : ""
            }
          />
        </Form.Item>
        <Form.Item className={Department.account} name="sex" labelCol={{ span: 4 }} label="性别">
        <Radio.Group>
            <Radio value="男">男</Radio>
            <Radio value="女">女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item className={Department.account} rules={validateRules.idcard} name="idcard" labelCol={{ span: 4 }} label="身份证号">
            
          <Input placeholder="身份证号" />
        </Form.Item>
        <Form.Item className={Department.account} name="phone" labelCol={{ span: 4 }} rules={validateRules.phone} label="手机号">
          <Input length='11' placeholder="手机号" />
        </Form.Item>
        
        <Form.Item className={Department.account} name="head" labelCol={{ span: 4 }} label="头像">
          <div>
            <Upload
              action={"http://localhost:21001/users/uploadheader"}
              listType="picture-card"
              fileList={file ? [file] : []}
              onPreview={handlePreview}
              method="POST"
              maxCount={1} // 限制只能上传一个文件
              onChange={handleChange}
            >
              {file ? null : uploadButton}
            </Upload>
            <Modal
              open={previewOpen}
              title={previewTitle}
              footer={null}
              onCancel={handleCancel}
            >
              <img alt="example" style={{ width: "100%" }} src={previewImage} />
            </Modal>
          </div>
        </Form.Item>
        <Form.Item>
          <div className={Department.director_btn_box}>
            <Button
              className={Department.btnCLickOK}
              type="primary"
              onClick={handleOkItemClick}
            >
              确认创建
            </Button>
            <Button
              className={Department.btnCLickOK}
              type="primary"
              onClick={handleOkItemClick}
            >
              返回上一级
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
}

export default AddAccount;
